package com.example.basesystem.controller;

import com.example.basesystem.common.Result;
import com.example.basesystem.dto.LoginDTO;
import com.example.basesystem.dto.RegisterDTO;
import com.example.basesystem.service.AuthService;
import com.example.basesystem.service.impl.AuthServiceImpl;
import com.example.basesystem.vo.InfoVo;
import com.example.basesystem.vo.LoginVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * 认证控制器
 */
@Tag(name = "认证管理", description = "认证相关接口")
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private AuthService authService;
    
    // 验证码过期时间，单位：毫秒
    private static final long CAPTCHA_EXPIRE_TIME = 5 * 60 * 1000;

    /**
     * 登录
     */
    @Operation(summary = "登录", description = "用户登录接口")
    @PostMapping("/login")
    public Result<LoginVO> login(@Validated @RequestBody LoginDTO loginDTO) {
        return authService.login(loginDTO);
    }

    /**
     * 获取用户详细信息
     */
    @Operation(summary = "获取信息", description = "获取用户详细信息接口")
    @GetMapping("/info")
    public Result<InfoVo> info() {
        return authService.info();
    }

    /**
     * 注册
     */
    @Operation(summary = "注册", description = "用户注册接口")
    @PostMapping("/register")
    public Result<Object> register(@Validated @RequestBody RegisterDTO registerDTO) {
        return authService.register(registerDTO);
    }

    /**
     * 退出登录
     */
    @Operation(summary = "退出登录", description = "用户退出登录接口")
    @PostMapping("/logout")
    public Result<Object> logout() {
        return authService.logout();
    }
    
    /**
     * 生成验证码
     */
    @Operation(summary = "获取验证码", description = "获取图片验证码")
    @GetMapping("/captcha")
    public void captcha(@RequestParam String key, HttpServletResponse response) throws IOException {
        // 设置响应的类型格式为图片格式
        response.setContentType("image/jpeg");
        // 禁止图像缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        
        // 生成验证码
          String code = generateCaptchaCode(4);
          // 存储验证码到AuthService
          ((AuthServiceImpl)authService).storeCaptcha(key, code);
        
        // 定时清除验证码
         new Thread(() -> {
             try {
                 Thread.sleep(CAPTCHA_EXPIRE_TIME);
                 // 使用AuthService清除验证码
                 ((AuthServiceImpl)authService).storeCaptcha(key, null);
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }).start();
        
        // 创建验证码图片
        int width = 100;
        int height = 40;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        
        // 设置背景色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);
        
        // 设置边框
        g.setColor(Color.LIGHT_GRAY);
        g.drawRect(0, 0, width - 1, height - 1);
        
        // 添加干扰线
        Random random = new Random();
        for (int i = 0; i < 20; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.setColor(getRandColor(100, 200));
            g.drawLine(x, y, x + xl, y + yl);
        }
        
        // 添加噪点
        float yawpRate = 0.05f;
        int area = (int) (yawpRate * width * height);
        for (int i = 0; i < area; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            image.setRGB(x, y, random.nextInt(255));
        }
        
        // 添加字符
        g.setFont(new Font("Arial", Font.BOLD, 25));
        for (int i = 0; i < code.length(); i++) {
            g.setColor(getRandColor(20, 130));
            g.drawString(String.valueOf(code.charAt(i)), 15 + i * 20, 30);
        }
        
        g.dispose();
        
        // 输出图片
        ImageIO.write(image, "JPEG", response.getOutputStream());
    }
    
    /**
     * 生成随机验证码
     */
    private String generateCaptchaCode(int length) {
        String chars = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ";//去除O、0
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(random.nextInt(chars.length())));
        }
        return sb.toString();
    }
    
    /**
     * 获取随机颜色
     */
    private Color getRandColor(int fc, int bc) {
        Random random = new Random();
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }
    
}